#include "AppUtil.h"

#include "core/AppContext.h"

namespace AppUtil {

int randomInt(int min, int max)
{
    return rand() % (max - min + 1) + min;
}

float randomFloat(float min, float max)
{
    return (float)rand() / RAND_MAX * (max - min) + min;
}

double randomDouble(double min, double max)
{
    return (double)rand() / RAND_MAX * (max - min) + min;
}

void showErrorMessageBox(std::exception& e)
{
    QMessageBox::critical(AppContext::mainWindow(), AppContext::ProductName(), e.what());
}

void showErrorMessageBox(const QString& message)
{
    QMessageBox::critical(AppContext::mainWindow(), AppContext::ProductName(), message);
}

std::wstring toWString(const std::string& str)
{
    int len;
    int slength = (int)str.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::string toString(const std::wstring& str)
{
    int len;
    int slength = (int)str.length() + 1;
    len = WideCharToMultiByte(CP_ACP, 0, str.c_str(), slength, 0, 0, 0, 0);
    char* buf = new char[len];
    WideCharToMultiByte(CP_ACP, 0, str.c_str(), slength, buf, len, 0, 0);
    std::string r(buf);
    delete[] buf;
    return r;
}

QString getAppFilePath(const QString& filePath)
{

    if (filePath.startsWith("<pcl>")) {
        QString path = AppSettings::get().pclRepository();
        if (!path.isEmpty()) {
            QString file = filePath;
            return file.replace(QString("<pcl>"), path);
        }
    } else if (filePath.startsWith("<pcl-data>")) {
        QString path = AppSettings::get().pclDataRepository();
        if (!path.isEmpty()) {
            QString file = filePath;
            return file.replace(QString("<pcl-data>"), path);
        }
    } else if (filePath.startsWith("<data>")) {
        QString path = AppDirectory::get().appExecuteDir() + "/data";
        if (!path.isEmpty()) {
            QString file = filePath;
            return file.replace(QString("<data>"), path);
        }
    }

    return filePath;
}

}; // namespace AppUtil
